/*LICENSE_BEGIN
 * ******************************************************************
 * All original parts of SoccerScope2003 have copyright (2003) by
 * Team YowAI, represented by Mr. Shuhei Shiota
 * The Department of Creative Informatics
 * The Graduate School of Information Science and Technology
 * The University of Tokyo
 * 
 * Additional classes (except libraries in /lib) were developed by 
 * the Dainamite Robocup-Team of the DAI-Labor, TU-Berlin 
 * (www.dai-labor.de)
 * 
 * Extended/new classes/packages are:
 *   soccerscope.analyzer.LogfileAnalyzer
 *   soccerscope.daistatistic.*
 *   soccerscope.daistatistic.charts.*
 *   soccerscope.daistatistic.tools.*
 *   soccerscope.db.*
 *   soccerscope.dialog.*
 *   soccerscope.model.PlayerWorldModel
 *   soccerscope.model.SimplePlayer
 *   soccerscope.net.AgentConnector
 *   soccerscope.training.*
 *   soccerscope.training.conditions.*
 * ******************************************************************
LICENSE_END*/
package soccerscope.daistatistic.tools;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 
 * a jpg writer
 */
public class JPGWriter {

	/**
	 * 
	 * saves an image to a file
	 * 
	 * @param BufferedImage
	 *            the image to save
	 * @param String
	 *            the file name without the .jpg extension
	 */
	public static void save(BufferedImage img, String nameWithoutExtension)
			throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream(0xfff);
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		JPEGEncodeParam param;
		param = encoder.getDefaultJPEGEncodeParam(img);
		param.setQuality(1f, true);

		encoder.encode(img, param);

		FileOutputStream fos = new FileOutputStream(nameWithoutExtension
				+ ".jpg");
		fos.write(out.toByteArray());
		fos.close();
		out.close();
	}

	/**
	 * 
	 * writes some text lines inton an image
	 * 
	 * @param String[]
	 *            the text lines
	 * @param BufferedImage
	 *            the image
	 * @return BufferedImage the image now with the textlines
	 */
	public static BufferedImage writeStringsToImage(String[] textLines,
			BufferedImage image) {

		// get the graphic context from the image
		Graphics g = image.createGraphics();
		g.setColor(Color.WHITE);

		// get y dimension
		int y = image.getHeight() - 2;

		// write the text lines to the image from south to north
		for (int i = 0; i < textLines.length; i++) {
			if (y > 0)
				g.drawString(textLines[i], 5, y);
			y = y - 14;
		}

		return image; // return an image
	}
}
